package BasicSyntax;

import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

public class BasicDemos {

    /**
     * 基础示例
     */
    public void Test()
    {
        //数组
        int[] arr = {1,7,3,8,5};
        System.out.println("3的下标是：" + Arrays.binarySearch(arr, 3));

        Arrays.sort(arr);
        System.out.println("排序结果：" + Arrays.toString(arr));

        int[] copy = Arrays.copyOfRange(arr, 1,3);
        System.out.println("切片[1,3)：" + Arrays.toString(copy));
        Arrays.fill(arr, 0);
        System.out.println("数组填充为0：" + Arrays.toString(arr));

        Arrays.fill(arr, 1, 4, 6);
        System.out.println("数组[1,4)填充为6：" + Arrays.toString(arr));

        //列表
        List<Integer> list = Arrays.asList(1, 6, 4, 9);
        System.out.print("列表输出：");
        for(Integer n: list){
            System.out.print(n + " ");
        }
        System.out.println();

        //字典
        Map<Integer, String> dic = new HashMap<>();
        dic.put(1, "zhang san");
        dic.put(2, "li si");
        System.out.println("字典输出：");
        for(Integer key: dic.keySet()){
            System.out.println(" " + key + ": " + dic.get(key));
        }

        //日期
        try {
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            Date dt1 = fmt.parse("2022-12-31");
            Date dt2 = fmt.parse("2021-12-31");
            Long ms = dt1.getTime() - dt2.getTime(); //毫秒
            Number days = ms / (1000 * 3600 * 24); //转为天数
            System.out.println(fmt.format(dt1) + "和" + fmt.format(dt2) + "相差：" + days + "天");
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }

        //文件读写
        String fileName = ".\\test.txt"; //当前项目文件夹下
        try{
            //文件写入(追加)
            RandomAccessFile file = new RandomAccessFile(fileName, "rw");
            file.seek(file.length()); //跳到末尾
            file.write(String.format("文件写入测试：%s\n", LocalDateTime.now()).getBytes());
            file.close();
            System.out.println();

            //文件读取
            FileInputStream fin = new FileInputStream(fileName);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fin.read(buffer)) > 0) {
                byte[] content = Arrays.copyOf(buffer,len);
                String str = new String(content, "UTF-8");
                System.out.println(str);
            }
            fin.close();
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
    }

}
